import { Body, Controller, Inject, Post, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { Public } from './auth.guard';
import { ApiOperation, ApiTags } from '@nestjs/swagger';

@ApiTags('auth 认证模块')
@Controller('auth')
export class AuthController {
  constructor(
    private authService: AuthService,
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
  ) {}

  @ApiOperation({ summary: '登录' })
  @Public()
  @Post('login')
  async signIn(@Body('phone') phone: string, @Body('code') code: string) {
    const cacheCode = await this.cacheManager.get(phone);
    this.cacheManager.del(phone);

    if (cacheCode !== code) {
      throw new UnauthorizedException();
    }
    return await this.authService.signIn(phone, code);
  }
}
